package com.qjj.studydainty;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;

/*
@qujianijn
*/
public class DownloadThread extends Thread {

    private String url;
    private String fileName;
    private Handler handler;
    private long fileLength;

    private static boolean cancle = false;

    public static final int DOWNLOAD_SUCCESS = 2;
    public static final int DOWNLOAD_START = 3;
    public static final int SDCARD_NO_PERMISSION = 1;
    public static final int DOWNLOAD_PROGRESSING = 4;

    public DownloadThread(String url, String fileName, long fileLength, Handler handler) {
        this.handler = handler;
        this.url = url;
        this.fileName = fileName;
        this.fileLength = fileLength;
    }

    public static void cancleThread() {
        cancle = true;
        Thread.interrupted();
    }

    @Override
    public void run() {

        URL downloadUrl = null;
        InputStream downloadInputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            downloadUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            httpURLConnection = (HttpURLConnection) downloadUrl.openConnection();

            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();
            downloadInputStream = httpURLConnection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String downloadPath;
        File downloadDir;
        File downloadFile;
        FileOutputStream fileOutputStream = null;

        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            handler.sendEmptyMessage(SDCARD_NO_PERMISSION);
            return;
        }

        downloadPath = Environment.getExternalStorageDirectory() + "/myDownload";
        downloadDir = new File(downloadPath);

        if (!downloadDir.exists()) {
            downloadDir.mkdirs();
        }

        downloadFile = new File(downloadDir, fileName);

        try {
            downloadFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fileOutputStream = new FileOutputStream(downloadFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        byte[] bytes = new byte[10240];
        int length;
        long downloadLength = 0;

        Message message = handler.obtainMessage();
        message.what = DOWNLOAD_START;
        long fileLengthByMB = fileLength / 1048576;
        message.obj = fileLengthByMB;
        handler.sendMessage(message);

        long lastTime = 0;
        long thisTime = 0;

        try {
            while ((length = downloadInputStream.read(bytes)) != -1 && !cancle) {
                if (fileOutputStream != null) {
                    fileOutputStream.write(bytes, 0, length);
                    downloadLength += length;

                    //更新下载进度
                    thisTime = Calendar.getInstance().getTimeInMillis();
                    if (thisTime - lastTime >= 1000) {
                        Message message1 = handler.obtainMessage();
                        message1.what = DOWNLOAD_PROGRESSING;
                        message1.obj = downloadLength;
                        handler.sendMessage(message1);
                        lastTime = thisTime;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (fileLength <= downloadLength+1024) {
            Message message1 = handler.obtainMessage();
            message1.what = DOWNLOAD_SUCCESS;
            message1.obj = fileName;
            handler.sendMessage(message1);
        }

        try {
            if (downloadInputStream != null) {
                downloadInputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
